Python (2nd Edition): Learn Python in One Day and Learn It Well. Python for Beginners with Hands-on Project. (Learn Coding Fast with Hands-On Project Book 1) by Chan Jamie & Publishing LCF

Python (2nd Edition): Learn Python in One Day and Learn It Well. Python for Beginners with Hands-on Project. (Learn Coding Fast with Hands-On Project Book 1) by Chan Jamie & Publishing LCF

Author:Chan, Jamie & Publishing, LCF
Language: eng
Format: epub, pdf
Publisher: Learn Coding Fast
Published: 2017-05-09T16:00:00+00:00


9.4 Properties

Now that we have a basic understanding of classes and objects, let us move on to discuss properties.

In the examples above, we notice that we can access an object’s instance variables using the dot operator. This makes it easy for us to read the variables and modify them when necessary. However, this flexibility also poses some problems. For instance, we may accidentally change the position of officeStaff1 to a non-existent position. Or we may change the pay of officeStaff1 to an incorrect amount.

To prevent such errors from occurring, we can use properties. Properties provide us with a way to check the values of the changes that we want to make before allowing the change to occur.

To demonstrate how properties work, we’ll add one for the variable position. Specifically, we’ll add a property to ensure that the variable position can only be set to either 'Basic' or 'Manager'.

However, before we do that, we want to first change the name of the instance variable from position to _position. Adding a single underscore in front of a variable name is a customary way to signal to other programmers that they should not touch this variable directly.

In Python programming, there is a commonly used phrase that says "we're all consenting adults here". We are all expected to behave like an adult. Adding a single underscore in front of a variable tells other programmers that you're trusting them to behave responsibly and not access that variable directly unless they have a compelling reason to. However technically, there is nothing stopping them from accessing the variable. If they so desire, they can still access it by writing

officeStaff1._position

Having said that, let’s just make the following changes to the classdemo.py file to let other ‘consenting adults’ know they should not access position directly:

Change the line

self.position = pPosition

in __init__ to

self._position = pPosition

and the line

return "Position = %s, Name = %s, Pay = %d" %(self.position, self.name, self.pay)

in __str__ to

return "Position = %s, Name = %s, Pay = %d" %(self._position, self.name, self.pay)

Next, let’s look at how to add a property for the _position variable:

Add the following lines to the Staff class in classdemo.py.

@property

def position(self):

print("Getter Method")

return self._position

@position.setter

def position(self, value):

if value == 'Manager' or value == 'Basic':

self._position = value

else:

print('Position is invalid. No changes made.')

Remember to indent the lines above when adding them to the Staff class. If you do not indent them, they do not belong to the Staff class.

The first line above (@property) is known as a decorator. We won’t go into details about what a decorator is, but simply put, it allows us to alter the functionality of the method that follows. In this case, it changes the first position() method to a property.

This means that it is telling the compiler that whenever users type

officeStaff1.position

it should use the position() method that follows to get the value.

This method simply prints the message “Getter Method” and returns the value of the variable _position. Due to the @property decorator that changes the method to a property, we do not have to type officeStaff1.position() to access the method.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Popular ebooks
Whisky: Malt Whiskies of Scotland (Collins Little Books) by dominic roskrow(55909)
What's Done in Darkness by Kayla Perrin(26521)
Shot Through the Heart: DI Grace Fisher 2 by Isabelle Grey(19007)
The Fifty Shades Trilogy & Grey by E L James(18959)
Shot Through the Heart by Mercy Celeste(18879)
Wolf & Parchment: New Theory Spice & Wolf, Vol. 10 by Isuna Hasekura and Jyuu Ayakura(16982)
Python GUI Applications using PyQt5 : The hands-on guide to build apps with Python by Verdugo Leire(16875)
Peren F. Statistics for Business and Economics...Essential Formulas 3ed 2025 by Unknown(16804)
Wolf & Parchment: New Theory Spice & Wolf, Vol. 03 by Isuna Hasekura and Jyuu Ayakura & Jyuu Ayakura(16698)
Wolf & Parchment: New Theory Spice & Wolf, Vol. 01 by Isuna Hasekura and Jyuu Ayakura & Jyuu Ayakura(16323)
The Subtle Art of Not Giving a F*ck by Mark Manson(14261)
The 3rd Cycle of the Betrayed Series Collection: Extremely Controversial Historical Thrillers (Betrayed Series Boxed set) by McCray Carolyn(14072)
Stepbrother Stories 2 - 21 Taboo Story Collection (Brother Sister Stepbrother Stepsister Taboo Pseudo Incest Family Virgin Creampie Pregnant Forced Pregnancy Breeding) by Roxi Harding(13420)
Scorched Earth by Nick Kyme(12715)
Drei Generationen auf dem Jakobsweg by Stein Pia(10922)
Suna by Ziefle Pia(10846)
Scythe by Neal Shusterman(10270)
International Relations from the Global South; Worlds of Difference; First Edition by Arlene B. Tickner & Karen Smith(9476)
Successful Proposal Strategies for Small Businesses: Using Knowledge Management ot Win Govenment, Private Sector, and International Contracts 3rd Edition by Robert Frey(9316)
This is Going to Hurt by Adam Kay(9098)